const jwt=require('jsonwebtoken')
const secret='ASDFASuouoiu@37897asdf'

//生成token
const createToken = (userInfo)=>{
    const token=jwt.sign(userInfo,secret,{expiresIn:5*60*60})
    return token
}

//校验token
const parse = (token) => {
    if(token) {
        try{ 
            return jwt.verify(token,secret)
        } catch (e) {
            return null
        }
    }
    return null
}

// 不需要带token的接口白名单
const NOT_AUTH_URL = ['/api/auth']

//判断请求的地址是否跟'白名单'
const isWhiteAuthURL = (path) => {
   return NOT_AUTH_URL.includes(path)
}

//判断请求是否带上token并校验token的有效性
const isAuthorized = (req) => {
    if(isWhiteAuthURL(req.path)){
        return true
    }
    const token = req.headers['x-token']
    const result = parse(token)
    if(result&&result.username){
        return true
    }
    return false
}
module.exports={
    isAuthorized,
    createToken
}